import 'dart:async';

import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_base_entity.dart';
import 'package:osc/models/entity/osc_user_tag.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/pages/common_page.dart';
import 'package:osc/ui/pages/my/search_tag.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///标签
class TagList extends StatefulWidget {
  const TagList({Key key,}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new TagListState();
  }
}

class TagListState extends State<TagList> {
  TagListState();

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscUserTag> list;


  RefreshController controller = RefreshController(initialRefresh: true);
  ScrollPhysics scrollPhysics = ScrollPhysics();
  ScrollController scrollController = ScrollController();


  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: false,
      child: ListView(
        children: <Widget>[
          buildSearch(),
          buildListView(),
        ],
      ),
    );
  }

  buildSearch(){
    return InkWell(
      onTap: (){
        jumpToPageForResult(CommonPage(title: "搜索标签", body: SearchTag()));
      },
      child: Container(
        padding: EdgeInsets.all(Dimens.gap_view_normal),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(top: BorderSide(color: Colors.black26), bottom: BorderSide(color: Colors.black26)),
        ),
        child: Container(
          padding: EdgeInsets.all(Dimens.gap_view_normal),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.black12),
            borderRadius: BorderRadius.all(Radius.circular(Dimens.view_radius_size_smaller)),
          ),
          child: Row(
            children: <Widget>[
              Image.asset(PdUtil.getImagePath("ic_search"), height: Dimens.view_item_icon_height_smaller, fit: BoxFit.fitWidth,),
              Expanded(
                child: Text("搜索你感兴趣的标签", style: MyTextStyle.HINT,),
              ),
              Image.asset(PdUtil.getImagePath("ic_cross"), height: Dimens.view_item_icon_height_smaller, fit: BoxFit.fitWidth,),
            ],
          ),
        ),
      ),
    );
  }

  buildListView(){
    return ListView.separated(
      shrinkWrap: true,
      primary: false,
      itemBuilder: (BuildContext context, int index) {
        if (size == 0) {
          return NoDataWidget();
        } else {
          return buildListItem(index);
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return SmallWidgets.buildLine();
      },
      itemCount: isLoadedData && size == 0? 1 : size,
//      physics: scrollPhysics,
    );
  }

  buildListItem(int index){
    OscUserTag item = list.elementAt(index);
    return Container(
      height: Dimens.view_button_height_normal,
      width: ScreenUtil.getInstance().screenWidth,
      child: ListView(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        controller: scrollController,
        children: <Widget>[
          Container(
            color: Colors.white,
            width: ScreenUtil.getScreenW(context),
            height: 40,
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal),
            child: Text(item.name, style: MyTextStyle.USER_LIST_TITLE,),
          ),
          Container(
            width: 60,
            height: 40,
            alignment: Alignment.center,
            color: Colors.deepOrange,
            child: InkWell(
              onTap: (){
                deleteTab(id: item.id, index: index);
                showTips("delete ${item.name}");
              },
              child: Text("delete", style: MyTextStyle.LIST_TAG_BUTTON,),
            ),
          )
        ],
      ),
    );
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    await httpRepository.getUserTagList().then((resp){
      isLoadedData = true;
      if(resp != null && resp.success){
        list = resp.listResult;
        size = list?.length??0;
      }
    });
    if(mounted) {
      setState(() {
        if(size > 0) {
          controller.loadNoData();
        }
        controller.refreshCompleted();
      });
    }
  }

  deleteTab({@required int id, @required index}) async{
    return await httpRepository.updateTagRelation(id: id).then((resp){
      if(resp != null && resp.success){
        list.removeAt(index);
        size = list?.length??0;
        if(mounted){
          setState(() {
            scrollController.jumpTo(0);
          });
        }
      }
    });
  }

  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      controller.requestRefresh(needMove: true);
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
